package org.freez4.spring.dependency.inject;

import org.freez4.spring.dependency.inject.domain.UserHolder;
import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Java 注解Setter注入Demo。
 *
 * @author 阿坤同学
 * @date 2023/12/10 21:18
 */
public class AnnotationDependencySetterInjectionDemo {

    private static final Logger logger = Logger.getLogger(AnnotationDependencySetterInjectionDemo.class.getName());

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册配置类
        applicationContext.register(AnnotationDependencySetterInjectionDemo.class);
        // 读取XML BeanDefinition
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
        String location = "classpath:/META-INF/dependency-lookup-context.xml";
        xmlReader.loadBeanDefinitions(location);
        // 刷新上下文
        applicationContext.refresh();

        UserHolder userHolder = applicationContext.getBean(UserHolder.class);
        logger.log(Level.INFO, () -> "通过Java注解方式setter注入User对象Demo: " + userHolder);

        // 关闭容器
        applicationContext.close();
    }

    @Bean
    public UserHolder userHolder(User user) {
        UserHolder userHolder = new UserHolder();
        userHolder.setUser(user);
        return userHolder;
    }
}
